package com.neardrug.services.impl;

import com.neardrug.common.Constants;
import com.neardrug.entity.Images;
import com.neardrug.exception.ServiceException;
import com.neardrug.mapper.ImagesMapper;
import com.neardrug.services.FileService;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Base64;
import java.util.List;

@Service
public class FileServiceImpl implements FileService {
    @Autowired
    private ImagesMapper imagesMapper;

    @Override
    public void downloadImagesResult(Integer taskId, HttpServletResponse response){
        //得到该taskid下的所有图片的List
        List<Images> imagesList = imagesMapper.selectByTaskId(taskId);
        //创建文档
        XWPFDocument document=new XWPFDocument();
        XWPFParagraph paragraph1 = document.createParagraph();//创建段落
        XWPFRun run1 = paragraph1.createRun();

        //遍历imagesList
        for (int i = 0; i < imagesList.size(); i++) {
            run1.setText("第"+(i+1)+"条目:");
            run1.addBreak();
            Images image = imagesList.get(i);
            //label标题
            Integer temLabel=image.getLabel();
            String label="";
            if (temLabel==1){
                label="反应过程图";
            }else if (temLabel==2){
                label="反应机理图";
            } else if (temLabel==3) {
                label="实验结果图";
            } else if (temLabel==4) {
                label="化学表征图";
            }
            run1.setText("图片类型:");
            run1.setText(label);
            run1.addBreak();
            //caption内容
            run1.setText("caption:");
            run1.setText(image.getCaption());
            run1.addBreak();
            //图片内容
            run1.setText("图片:");
            String base64Data=image.getImg();
            byte[] imageBytes = Base64.getDecoder().decode(base64Data);
            try (InputStream imageStream = new ByteArrayInputStream(imageBytes)) {
                run1.addPicture(imageStream,
                        XWPFDocument.PICTURE_TYPE_PNG, // 图片类型
                        "image.png", // 图片文件名
                        500 * 9525, // 图片宽度（以EMU为单位，1点 = 9525 EMU）
                        300 * 9525  // 图片高度
                );
            } catch (IOException | InvalidFormatException e) {
                throw new ServiceException(Constants.CODE_500,"下载有误");
            }
            run1.addBreak();
            //footnote
            run1.setText("footnote:");
            run1.setText(image.getFootnote());
            run1.addBreak();
            //分割下一条
            run1.setText("");
            run1.addBreak();
        }

        // 设置响应头，告诉浏览器这是一个文件下载请求
        response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
        response.setHeader("Content-Disposition", "attachment; filename=output.docx");

        // 通过响应输出流写出文件内容
        try (OutputStream out = response.getOutputStream()) {
            document.write(out);
        } catch (IOException e) {
            throw new ServiceException(Constants.CODE_500,"文件下载有误");
        }
    }

}
